<template>
  <div class="box-list-container">
    <div class="box-query-form">
      <el-form :model="queryParam" label-width="auto" label-position="right" :gutter="24">
        <el-row>
          <el-col :xl="6" :lg="6" :md="12" :sm="24">
            <el-form-item label="账号数据:">
              <el-input v-model="queryParam.number" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :xl="12" :lg="12" :md="12" :sm="24">
            <el-form-item label="时间范围:">
              <el-date-picker
                v-model="queryParam.timeTemp"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
                @change="getTimeScope"
              />
            </el-form-item>
          </el-col>
          <template v-if="toggleSearchStatus">
            <el-col :xl="6" :lg="6" :md="12" :sm="24">
              <el-form-item label="类别名称:">
                <el-input v-model="queryParam.className" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :xl="6" :lg="6" :md="12" :sm="24">
              <el-form-item label="备注1:">
                <el-input v-model="queryParam.Remarks1" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :xl="6" :lg="6" :md="12" :sm="24">
              <el-form-item label="备注2:">
                <el-input v-model="queryParam.Remarks2" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :xl="6" :lg="6" :md="12" :sm="24">
              <el-form-item label="备注3:">
                <el-input v-model="queryParam.Remarks3" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col v-if="userInfo.userType === '666'" :xl="6" :lg="6" :md="12" :sm="24">
              <el-form-item label="所属会员:">
                <el-select v-model="queryParam.UserId" placeholder="请选择">
                  <el-option v-for="item in memberUserList" :key="item.id" :label="item.loginNum" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-col :xl="6" :lg="6" :md="12" :sm="24" class="table-search-btn">
            <el-button icon="el-icon-refresh" @click="searchReset">重置</el-button>
            <el-button type="primary" icon="el-icon-search" @click="searchQuery">查询</el-button>
            <el-link style="margin-left: 10px;" type="primary" :underline="false" @click="handleToggleSearch">
              {{ toggleSearchStatus ? '收起' : '展开' }}
              <i :class="toggleSearchStatus ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />
            </el-link>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="box-table">
      <div class="table-title">
        <div class="table-title-left">
          {{ tableTitle }}
        </div>
        <div>
          <el-button v-if="useState === 0 || useState === 1" plain class="btnAdd" icon="el-icon-plus" @click="handleAddPaste()">粘贴文本批量上传</el-button>
          <el-button v-if="useState === 0 || useState === 1" plain class="btnAdd" icon="el-icon-plus" @click="handleAdd('新增')">新增一条</el-button>
          <el-button type="success" icon="el-icon-upload" @click="importExcelData">上传excel</el-button>
          <el-button type="success" icon="el-icon-download" :loading="exportExcelLoading" @click="exportExcelData">{{ exportBtnName }}</el-button>
        </div>
      </div>
      <!-- 批量操作 -->
      <div v-if="selectedRowList.length" class="batchAction">
        <div class="batchAction-left">
          <el-dropdown>
            <el-button>
              更多菜单 <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <div @click="batchDelete"><i class="el-icon-delete" />删除</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div class="batchAction-right">
          已选择
          <span style="font-weight: 700">
            <el-link type="primary" :underline="false">{{ selectedRowList.length }}</el-link>
          </span>项
          <el-link type="primary" :underline="false" style="margin-left: 24px;" @click="onClearSelected">清空</el-link>
        </div>
      </div>
      <el-table ref="table" :data="dataSource" @selection-change="onSelectChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="60" type="index" />
        <el-table-column v-if="userInfo.userType === '666'" label="所属用户" prop="UserNum" min-width="100" />
        <el-table-column label="账号数据" prop="number" min-width="200" />
        <!-- <el-table-column label="账号类别" prop="numClass" min-width="200" /> -->
        <el-table-column label="备注1" prop="Remarks1" min-width="100" />
        <el-table-column label="备注2" prop="Remarks2" min-width="100" />
        <el-table-column label="备注3" prop="Remarks3" min-width="100" />
        <el-table-column label="创建时间" prop="createTime" width="170" />
        <el-table-column label="更新时间" prop="updateTime" width="170" />
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit('编辑', scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" style="margin-left: 10px" @confirm="handleDelete(scope.row[guidFieldName])">
              <el-button slot="reference" type="text" style="color: red;">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
        <div slot="empty" class="emptyBg">
          <img src="@/assets/img/emptyData.png">
        </div>
      </el-table>
      <div class="box-paging">
        <pagination
          v-show="ipagination.total > 0"
          layout="total, sizes, prev, pager, next"
          :total="ipagination.total"
          :page.sync="ipagination.pageNum"
          :limit.sync="ipagination.pageSize"
          @pagination="loadData"
        />
      </div>
    </div>
    <!-- 抽屉 -->
    <updateDrawerModel ref="modalForm" @ok="modalFormOk" />
    <!-- 粘贴上传 -->
    <pasteTextBatchUploadModel ref="pasteTextBatchUploadModel" @ok="modalFormOk" />
    <!-- 导入excel弹窗 -->
    <importExcelModel ref="importExcelModel" @ok="modalFormOk" />
  </div>
</template>

<script>
import { listMixin } from '@/mixins/listMixin'
import { postAction } from '@/api/manage'
import Pagination from '@/components/Pagination'
import updateDrawerModel from './updateDrawerModel.vue'
import { api_getMemberUser } from '@/api/user'
import pasteTextBatchUploadModel from './pasteTextBatchUploadModel.vue'
import excel from 'lay-excel'
import { antiShake } from '@/utils'
import importExcelModel from '@/components/xm/importExcelModel'

export default {
  components: {
    Pagination,
    importExcelModel,
    updateDrawerModel,
    pasteTextBatchUploadModel
  },
  mixins: [listMixin],
  props: {
    numClass: {
      type: String,
      default: ''
    },
    useState: {
      type: [Number, String],
      default: ''
    }
  },
  data() {
    return {
      guidFieldName: 'id',
      toggleSearchStatus: false,
      exportBtnName: '导出全部',
      userInfo: {},
      timeTemp: [],
      memberUserList: [],
      exportExcelLoading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      url: {
        list: 'NumberData.aspx?action=GetList',
        delete: 'NumberData.aspx?action=Delete',
        deleteBatch: 'NumberData.aspx?action=DeleteBatch'
      }
    }
  },
  watch: {
    numClass(newV, oldV) {
      this.loadData(1)
    }
  },
  created() {
    this.userInfo = this.$ls.get('USER_INFO')
    if (this.userInfo.userType === '666') {
      this.getMemberUser()
    }
    if (this.useState === 0) {
      this.tableTitle = '全部'
      this.exportBtnName = '导出全部'
    } else if (this.useState === 1) {
      this.tableTitle = '未使用列表'
      this.exportBtnName = '导出未使用'
    } else if (this.useState === 2) {
      this.tableTitle = '使用中列表'
      this.exportBtnName = '导出使用中'
    } else if (this.useState === 3) {
      this.tableTitle = '已使用列表'
      this.exportBtnName = '导出已使用'
    }
  },
  mounted() {
  },
  methods: {
    // 上传excel
    importExcelData() {
      this.$refs.importExcelModel.show({
        fileName: '账号数据导入模板',
        importUrl: 'NumberData.aspx?action=ImportExcel',
        importType: 'GetNumberBusiness' // 标识
      })
    },
    // 生成excel
    createExcel(data) {
      if (data.length === 0) {
        this.$message.info('无数据可导出')
        this.exportExcelLoading = false
        return
      }
      // 过滤需要的列
      const filterColNameArr = ['numClass', 'number', 'Remarks1', 'Remarks2', 'Remarks3', 'useState', 'UserNum', 'createUser', 'createTime', 'updateUser', 'updateTime']

      data = excel.filterExportData(data, filterColNameArr)
      console.log('导出的数据data', data)
      data.forEach(v => {
        if (v.useState === '1') {
          v.useState = '未使用'
        } else if (v.useState === '2') {
          v.useState = '使用中'
        } else if (v.useState === '3') {
          v.useState = '已使用'
        }
      })
      // 加列头
      data.unshift({
        numClass: '类别名称',
        number: '账号数据',
        Remarks1: '备注1',
        Remarks2: '备注2',
        Remarks3: '备注3',
        useState: '状态',
        UserNum: '所属用户',
        createUser: '创建人',
        createTime: '创建时间',
        updateUser: '更新人',
        updateTime: '更新时间'
      })
      // 执行导出函数，系统会弹出弹框
      excel.exportExcel(
        {
          sheet1: data
        },
        `导出账号数据${this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}.xlsx`,
        'xlsx'
      )
      this.exportExcelLoading = false
      this.$message.success(`类别 ${this.numClass} ,状态 ${this.tableTitle} 导出成功`)
    },
    // 导出数据
    exportExcelData() {
      antiShake(() => {
        this.$store.dispatch('app/setLoading', true)
        this.exportExcelLoading = true
        const p = { pageNum: 1, pageSize: 1000000 }
        if (this.numClass !== '全部') {
          if (!this.numClass) {
            this.numClass = '全部'
          }
          p.numClass = this.numClass
        }
        if (this.exportBtnName === '导出全部') {
          p.useState = '0'
        } else if (this.exportBtnName === '导出未使用') {
          p.useState = '1'
        } else if (this.exportBtnName === '导出使用中') {
          p.useState = '2'
        } else if (this.exportBtnName === '导出已使用') {
          p.useState = '3'
        }
        postAction(this.url.list, p).then((res) => {
          console.log('导出的数据', res)
          if (res.code === 1) {
            this.createExcel(res.data.list)
          } else {
            this.exportExcelLoading = false
          }
        }).finally(() => {
          this.$store.dispatch('app/setLoading', false)
        })
      }, 600)
    },
    // 开始时间结束时间
    getTimeScope(e) {
      console.log('开始结束时间', e)
      if (e) {
        this.queryParam.ctime1 = this.$moment(e[0]).format('YYYY-MM-DD HH:mm:ss')
        this.queryParam.ctime2 = this.$moment(e[1]).format('YYYY-MM-DD HH:mm:ss')
      } else {
        this.queryParam.ctime1 = ''
        this.queryParam.ctime2 = ''
      }
    },
    // 粘贴文本批量上传
    handleAddPaste() {
      if (!this.numClass || this.numClass === '全部') {
        this.$message.warning('请选择要上传的类别!')
      } else {
        this.$refs.pasteTextBatchUploadModel.numClass = this.numClass
        this.$refs.pasteTextBatchUploadModel.show()
      }
    },
    // 获取会员
    getMemberUser() {
      api_getMemberUser().then((res) => {
        console.log('获取会员', res)
        if (res.code === 1) {
          this.memberUserList = res.data
        }
      })
    },
    // // 加载数据列表
    // loadData(arg) {
    //   if (!this.url.list) {
    //     this.$message.error('请设置url.list属性!')
    //     return
    //   }
    //   // 若传入参数1则加载第一页的内容
    //   if (arg === 1) {
    //     this.ipagination.pageNum = 1
    //   }
    //   const params = this.getQueryParams() // 查询条件
    //   this.$store.dispatch('app/setLoading', true)
    //   postAction(this.url.list, params).then((res) => {
    //     if (res.code === 1) {
    //       const { list, total } = res.data
    //       this.dataSource = list
    //       if (total) {
    //         this.ipagination.total = total
    //       } else {
    //         this.ipagination.total = 0
    //       }
    //     } else {
    //       this.$message.warning(res.message || '操作失败！')
    //     }
    //   }).finally(() => {
    //     this.$store.dispatch('app/setLoading', false)
    //   })
    // },
    // 添加查询参数 默认加空对象
    addQueryParams() {
      return {
        numClass: this.numClass,
        useState: this.useState
      }
    },
    // 展开收起
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    }
  }
}
</script>

<style lang="scss" scoped>
.box-container .box-query-form{
  padding: 0;
}
.box-table{
  margin-top: 0;
  padding-top: 0;
}
</style>
